<template>
  <div class="view-fill">
    <div
      v-if="
        !inventoryDataEntryInfo.visible &&
        !dataEntryDetailsInfo.visible &&
        !batchDataInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :needReturn="false"
        :btnList="fullInfo.btnList"
        :newFullScreenClass="newFullScreenClass"
      >
        <template v-slot:full-button>
          <el-input
            v-model="scanFilter.locationNo"
            class="not-mongolia"
            type="input"
            style="width: 250px; margin-right: 10px"
            placeholder="请扫描/选择/输入货位"
          >
            <template #append>
              <el-icon @click="selectScanGoodsLocation"><MoreFilled /></el-icon>
            </template>
          </el-input>
          <ScanInputBox
            :tableData="tableInfo.data"
            v-model:query="scanFilter"
            :api="scanApi"
            :disabled="infoList.data.status !== 4"
            :selectObj="individualInfo.selectObj"
            :isSysGroup="tableInfo.isSysGroup"
            inventoryType="main"
            @callback="onCallBackScanData"
            style="margin-right: 10px"
          />
          <el-input
            type="text"
            style="width: 180px; margin-right: 10px"
            v-model="filterInfo.data.keyword"
            clearable
            placeholder="请输入批号"
            @keyup.enter.native="search"
            @input="(e) => (filterInfo.data.keyword = validSe(e))"
          />
          <el-button @click="search">搜索</el-button>
        </template>
        <div id="table-list">
          <div class="model-panel">
            <div class="model-panel-title">
              <p>{{ $t('basic_information') }}</p>
            </div>
            <div class="model-panel-body">
              <!-- form -->
              <BasicInformation :info="infoList" />
            </div>
          </div>
          <div class="model-panel" v-if="infoList.data.useSub === 1">
            <div class="model-panel-title">
              <Tooltip :text="'子盘点单'"></Tooltip>
            </div>
            <div class="model-panel-body">
              <NewPageFilter :filter-btn="filterItemInfo.list"> </NewPageFilter>
              <PageTable
                :pager="false"
                v-model:data="tableItemInfo.data"
                :api="tableItemInfo.api"
                :field-list="tableItemInfo.fieldList"
                :handle="tableItemInfo.handle"
                :check-box="false"
                :highlight-row="false"
              >
              </PageTable>
            </div>
          </div>
          <div class="model-panel" id="table-box">
            <div class="model-panel-title div-flex">
              <Tooltip :text="$t('detailInfo')"></Tooltip>
              <ModelTips
                :items="modelTipsInfo.items"
                :title="modelTipsInfo.title"
                :brackets="true"
              />
            </div>
            <div class="model-panel-body">
              <!-- 条件栏 -->
              <NewPageFilter
                v-if="infoList.data.status === 4"
                :filter-btn="filterInfo.list"
              >
                <template v-slot:filter-selectMode>
                  <el-select
                    @change="getList"
                    clearable
                    v-model="filterInfo.query.queryParams.selectMode"
                  >
                    <el-option
                      :value="item.code"
                      v-for="(item, index) in filterInfo.data.selectModeOption"
                      :key="index"
                      :label="item.name"
                    />
                  </el-select>
                </template>
                <template v-slot:filter-exportData>
                  <!-- <el-button :disabled="!canExport" @click="exportData()"
                    >出库处理
                  </el-button> -->
                  <el-dropdown :disabled="!canExport" @command="exportData">
                    <el-button :disabled="!canExport">
                      出库处理<el-icon class="el-icon--right"
                        ><arrow-down
                      /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="item in businessTypeOptions"
                          :key="item.code"
                          :command="item.code"
                          >{{ item.name }}</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </NewPageFilter>
              <div class="flex_full_item">
                <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                  <!-- 表格 -->
                  <PageTable
                    v-model:ref-obj="tableInfo.ref"
                    :refresh="tableInfo.refresh"
                    :init-curpage="tableInfo.initCurpage"
                    v-model:data="tableInfo.list"
                    :pager="false"
                    :row-class-name="rowClassName"
                    :highlightRow="false"
                    :check-box="true"
                    :reserveSelection="true"
                    :tab-index="true"
                    :index-method="indexMethod"
                    :summaries-fn="getSummaries"
                    :summary="tableInfo.summary"
                    :summaryFieldList="tableInfo.summaryFieldList"
                    :field-list="tableInfo.fieldList"
                    :handle="tableInfo.handle"
                    @handleEvent="handleEvent"
                  >
                    <template v-slot:col-locationNo="scope">
                      <el-input
                        v-if="
                          tableInfo.isSysGroup
                            ? scope.row.stockCalcQty === 0 &&
                              tableInfo.groupList.includes('goodsLocationId')
                            : scope.row.stockCalcQty === 0
                        "
                        v-model="scope.row.locationNo"
                        class="not-mongolia"
                        type="input"
                        :disabled="true"
                        placeholder="请选择货位"
                      >
                        <template #append>
                          <el-icon @click="selectGoodsLocation(scope.row)"
                            ><MoreFilled
                          /></el-icon>
                        </template>
                      </el-input>
                      <span v-else>{{ scope.row.locationNo || '' }}</span>
                    </template>
                    <template v-slot:col-batchNumber="scope">
                      <el-input
                        v-if="
                          tableInfo.isSysGroup
                            ? scope.row.stockCalcQty === 0 &&
                              scope.row.codeType !== 3 &&
                              tableInfo.groupList.includes('batchNumber')
                            : scope.row.stockCalcQty === 0 &&
                              scope.row.codeType !== 3
                        "
                        v-model="scope.row.batchNumber"
                        :maxlength="25"
                        @blur="batchNumberBlur($event, scope.row, scope.$index)"
                        @input="(e) => (scope.row.batchNumber = validSe(e))"
                      />
                      <p v-else>
                        {{ scope.row.batchNumber || '-' }}
                      </p>
                    </template>
                    <template v-slot:col-productionDate="scope">
                      <el-date-picker
                        v-if="
                          tableInfo.isSysGroup
                            ? scope.row.stockCalcQty === 0 &&
                              scope.row.codeType !== 3 &&
                              tableInfo.groupList.includes('productionDate')
                            : scope.row.stockCalcQty === 0 &&
                              scope.row.codeType !== 3
                        "
                        v-model="scope.row.productionDate"
                        value-format="YYYY-MM-DD"
                        :disabled-date="
                          productionTimePickerOptions.disabledDate
                        "
                      />
                      <p v-else>
                        {{ scope.row.productionDate || '-' }}
                      </p>
                    </template>
                    <template v-slot:col-validityDate="scope">
                      <el-date-picker
                        v-if="
                          tableInfo.isSysGroup
                            ? scope.row.stockCalcQty === 0 &&
                              scope.row.codeType !== 3 &&
                              tableInfo.groupList.includes('validityDate')
                            : scope.row.stockCalcQty === 0 &&
                              scope.row.codeType !== 3
                        "
                        v-model="scope.row.validityDate"
                        value-format="YYYY-MM-DD"
                        :disabled-date="validityTimePickerOptions.disabledDate"
                      />
                      <p v-else>
                        {{ scope.row.validityDate || '-' }}
                      </p>
                    </template>
                    <template v-slot:col-price="scope">
                      <el-form-item
                        v-if="
                          tableInfo.isSysGroup
                            ? scope.row.stockCalcQty === 0 &&
                              tableInfo.groupList.includes('price')
                            : scope.row.stockCalcQty === 0
                        "
                        :prop="`data.${scope.$index}.price`"
                        :rules="
                          scope.$index >= 0
                            ? [
                                {
                                  validator: $validate.positiveMoneyZero,
                                  trigger: 'blur',
                                },
                              ]
                            : []
                        "
                      >
                        <el-input-number
                          v-model.number="scope.row.price"
                          controls-position="right"
                          :precision="systemConfig.price_precision"
                          :min="0"
                          @change="
                            changePrice($event, `data.${scope.$index}.price`)
                          "
                          :max="999999999999999"
                          :step="1"
                        ></el-input-number>
                      </el-form-item>
                      <p v-else>{{ $fn.TripartiteMethod(scope.row.price) }}</p>
                    </template>
                    <template v-slot:col-qty="scope">
                      <template v-if="!tableInfo.isSysGroup">
                        <el-form-item class="margin-bottom">
                          <div class="page-table-input-number-wrapper">
                            <div class="page-table-input-number-left">
                              <div class="page-table-input-number-item">
                                <el-form-item
                                  :prop="`data.${scope.$index}.largeUnitQty`"
                                  :rules="
                                    scope.$index >= 0
                                      ? [
                                          {
                                            validator:
                                              $validate.positiveAndZero,
                                            trigger: 'blur',
                                          },
                                        ]
                                      : []
                                  "
                                >
                                  <el-input-number
                                    style="width: 100%; margintop: 18px"
                                    v-model.lazy="scope.row.largeUnitQty"
                                    clearable
                                    controls-position="right"
                                    :precision="
                                      scope.row.qtyOperateMode === 0 ||
                                      scope.row.qtyOperateMode === 2
                                        ? 0
                                        : systemConfig.qty_show_precision
                                    "
                                    @change="
                                      changeLarge(
                                        $event,
                                        scope.row,
                                        `data.${scope.$index}.largeUnitQty`
                                      )
                                    "
                                    :min="0"
                                    :max="largeMax(scope.row)"
                                  />
                                </el-form-item>
                                <div class="page-table-input-number-item-unite">
                                  {{ scope.row.unitName }}
                                </div>
                              </div>
                              <div
                                class="page-table-input-number-item"
                                v-if="
                                  scope.row.unitConvertCoefficient > 1 &&
                                  scope.row.qtyOperateMode === 2
                                "
                              >
                                <el-form-item>
                                  <el-input-number
                                    style="width: 100%; margintop: 18px"
                                    v-model.lazy="scope.row.smallUnitQty"
                                    clearable
                                    controls-position="right"
                                    :precision="0"
                                    :min="0"
                                    @change="changeSmall($event, scope.row)"
                                    :max="smallMax(scope.row)"
                                  />
                                </el-form-item>
                                <div class="page-table-input-number-item-unite">
                                  {{ scope.row.calcUnitName }}
                                </div>
                              </div>
                            </div>
                            <div
                              class="page-table-input-number-right"
                              v-if="scope.row.qtyOperateMode === 2"
                            >
                              {{ $fn.qtyFormatter(scope.row.qty) }}
                            </div>
                          </div>
                        </el-form-item>
                      </template>
                      <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                    </template>
                  </PageTable>
                </el-form>
              </div>
            </div>
          </div>
        </div>
      </NewFullScreen>

      <!-- 新增修改弹窗 -->
      <PageDialog
        v-if="dialogInfo.visible"
        :title="dialogInfo.title[dialogInfo.type]"
        v-model:visible="dialogInfo.visible"
        :width="dialogInfo.width"
        :bt-loading="dialogInfo.btLoading"
        :bt-list="dialogInfo.btList"
      >
        <!-- form -->
        <PageForm
          class="paddingBox order-model-formBox flex_wrap_start_start"
          v-model:ref-obj="formItemInfo.ref"
          :data="formItemInfo.data"
          :field-list="formItemInfo.fieldList"
          :rules="formItemInfo.rules"
          :label-width="formItemInfo.labelWidth"
        />
      </PageDialog>

      <DataEntryIndividualDetails
        v-if="individualInfo.visible"
        v-model:show-dialog="individualInfo.visible"
        v-model:query="individualInfo.query"
        :info="individualInfo.productInfo"
        :api="individualInfo.api"
        :del-api="individualInfo.delApi"
        :tableData="tableInfo.data"
        :groupList="tableInfo.groupList"
        :saveApi="individualInfo.saveApi"
        :isSysGroup="tableInfo.isSysGroup"
        :isConsignBusiness="infoList.data.isConsignBusiness"
        :mergeCustomizeUserVO="filterInfo.query.customizeUserVO"
        tableKey="wmsStockInventoryDataEntryIndividual-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO"
        @callback="selectedIndividualDetails"
      ></DataEntryIndividualDetails>
      <NewSelectProduct
        v-if="selectProductInfo.visible"
        v-model:showDialog="selectProductInfo.visible"
        v-model:query="selectProductInfo.query"
        :table-key="selectProductInfo.tableKey"
        :queryParams="selectProductInfo.queryParams"
        @callback="selectProduct"
      />
    </div>
    <!-- 数据录入 -->
    <individual-item-details
      v-if="inventoryDataEntryInfo.visible"
      v-model:visible="inventoryDataEntryInfo.visible"
      :tableRow="inventoryDataEntryInfo.tableRow"
      :title="inventoryDataEntryInfo.title"
      :orderId="infoList.data.id"
      :depotAllowFrozenInventory ="infoList.data.depotAllowFrozenInventory"
      :inventoryOrderProducts="
        infoList.data.inventoryOrderProducts &&
        infoList.data.inventoryOrderProducts.length
          ? infoList.data.inventoryOrderProducts
          : []
      "
      :inventoryOrderGoodsLocations="
        infoList.data.inventoryOrderGoodsLocations &&
        infoList.data.inventoryOrderGoodsLocations.length
          ? infoList.data.inventoryOrderGoodsLocations
          : []
      "
      :goodsLocationProductIds="
        infoList.data.goodsLocationProductIds &&
        infoList.data.goodsLocationProductIds.length
          ? infoList.data.goodsLocationProductIds
          : []
      "
      @callback="handleCallback"
    />
    <dataEntryDetails
      v-if="dataEntryDetailsInfo.visible"
      v-model:visible="dataEntryDetailsInfo.visible"
      :tableRow="dataEntryDetailsInfo.tableRow"
      :title="dataEntryDetailsInfo.title"
      @callback="handleCallback"
    />
    <ChosePrinter
      :visible="printerInfo.visible"
      @callBack="handlePrinterCallBack"
    />
    <!--选择供应商-->
    <SelectSupplier
      v-if="selectProductSupplier.visible"
      v-model:show-dialog="selectProductSupplier.visible"
      :check-box="false"
      :highlight-row="true"
      :api="selectProductSupplier.api"
      v-model:query="selectProductSupplier.query"
      @callback="selectSupplierCallback"
    />
    <!--出库处理弹窗-->
    <batchData
      v-if="batchDataInfo.visible"
      v-model:visible="batchDataInfo.visible"
      :selectionsData="tableInfo.selections"
      :baseData="batchDataInfo.baseData"
      :businessType="batchDataInfo.businessType"
      :title="batchDataInfo.title"
      :orderId="tableRow.id"
      :isConsignBusiness="tableRow.isConsignBusiness"
      @callback="batchDataCallback"
      @returnBack="returnBack"
    />
    <SelectCargoSpace
      v-if="selectLocationNoInfo.visible"
      v-model:show-dialog="selectLocationNoInfo.visible"
      row-key="goodsLocationId"
      v-model:query="selectLocationNoInfo.query"
      :highlightRow="true"
      :checkBox="false"
      :save-empty="false"
      :showDepot="false"
      @callback="selectLocationNoCallBack"
    />
    <SelectCargoSpace
      v-if="selectScanLocationNoInfo.visible"
      v-model:show-dialog="selectScanLocationNoInfo.visible"
      row-key="goodsLocationId"
      v-model:query="selectScanLocationNoInfo.query"
      :highlightRow="true"
      :checkBox="false"
      :save-empty="false"
      :showDepot="false"
      @callback="selectScanLocationNoCallBack"
    />
  </div>
</template>

<script setup name="inventory-data-entry">
import {
  getInventoryDetailsCustomizeListAll,
  getInventoryOrderById,
  inventoryOrderProcessDiff,
  inventoriesScans,
  subInventoryOrderAll,
  addSubInventoryOrder,
  updateSubInventoryOrder,
  subInventoryOrderBatchDelete,
  subInventoryOrderSubmit,
  inventoriesMergeSub,
  inventoryOrderDetailExtAll,
  inventoryDetailsAddProduct,
  inventoryDetailsDelete,
  inventoryDetailsDeleteByGroups,
  inventoryOrderDetailExtUpdate,
  inventoriesExcel,
  inventoryDetailsUpdate,
  inventoryDetailsUpdateByMerge,
  inventoryDetailDelete,
  getInventoryOrderPrint,
  subInventoryOrderRevoke,
} from '@/api/stock'
import { productCodePrint, getSupplierProductPage } from '@/api/core'
import ScanInputBox from './components/ScanInputBox'
import batchData from './components/batchData'
import _ from 'lodash'
import { getCustomizeSetting } from '@/api/customize'
import { ElMessage } from 'element-plus'
import { fatchTemplateByCode } from '@/api/base'

const { proxy } = getCurrentInstance()
const DataEntryIndividualDetails = defineAsyncComponent(() =>
  import('./DataEntryIndividualDetails')
)
const IndividualItemDetails = defineAsyncComponent(() =>
  import('./IndividualItemDetails')
)
const dataEntryDetails = defineAsyncComponent(() =>
  import('./dataEntryDetails')
)
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: () => {
      return ''
    },
  },
  tableRow: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const businessTypeOptions = computed(() => {
  return (
    proxy.$store.state.permission.dict['wms_inventory_loss_business_type'] || []
  )
})
const listPage = ref(0)
const loading = ref(false)
const box = ref(undefined)
const oldDataIndex = ref(-1)
//颜色标识
const modelTipsInfo = ref({
  title: '盘点状态',
  items: [
    {
      label: '盘盈',
      style: { width: '10px', height: '10px', background: '#F7C2C2' },
    },
  ],
})
const selectLocationNoInfo = ref({
  visible: false,
  row: {},
  query: {
    status: 1,
    depotId: '',
    idMult: '',
  },
})
const selectScanLocationNoInfo = ref({
  visible: false,
  query: {
    status: 1,
    depotId: '',
    idMult: '',
  },
})
//数据录入相关
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const inventoryDataEntryInfo = ref({
  visible: false,
  title: '',
  tableRow: {},
})
const formItemInfo = ref({
  ref: null,
  data: {
    roomNo: '',
    remark: '',
    isConsignBusiness: '',
  },
  fieldList: [
    {
      label: '房间号',
      value: 'roomNo',
      type: 'input',
      required: true,
      maxlength: 32,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {},
  labelWidth: '100px',
})
const scrollTop = ref('')
// 弹窗相关
const dialogInfo = ref({
  title: {
    create: '新增',
    update: '修改',
  },
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveItem,
      saveLoading: false,
      show: true,
    },
  ],
})
const filterItemInfo = ref({
  query: {
    orderId: props.tableRow.id,
    sort: 'create_time desc',
  },
  list: [
    { type: 'button', label: '新增', event: create, show: true },
    { type: 'button', label: '合并', event: concatData, show: true },
  ],
})
// 表格相关
const tableItemInfo = ref({
  data: [],
  fieldList: [
    { label: '单号', value: 'subOrderNo' },
    { label: '房间号', value: 'roomNo' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
    { label: '盘点人', value: 'inventoryUserName' },
    { label: '盘点时间', value: 'inventoryTime' },
    { label: '状态', value: 'statusValue' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '提交',
        event: submit,
        show: true,
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '修改',
        event: update,
        show: true,
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '数据录入',
        event: dataEntry,
        show: true,
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('inventories:revokeSub'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '查看',
        event: getItemDetails,
        show: true,
        ifRender: function (row) {
          return row.status === 3 || row.status === 2
        },
      },
      {
        label: '删除',
        event: deleteItem,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: function (row) {
          return row.status === 1
        },
      },
    ],
  },
})
const scanFilter = ref({
  orderId: props.tableRow.id,
  locationNo: '',
  isConsignment: '',
})
const scanApi = ref(inventoriesScans)
const productionTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
  },
})
const formRefs = ref([])
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRow.id,
      },
    },
    queryParams: {
      selectMode: '',
    },
  },
  data: {
    keyword: '',
    selectModeOption: proxy.$store.state.permission.dict['selectMode'] || [],
  },
  list: [
    {
      label: '添加产品',
      type: 'button',
      event: addProduct,
      show: computed(() => {
        return infoList.value.data.isConsignBusiness === 0
      }),
    },
    { label: '完成', type: 'button', event: processDiff },
    { label: '出库处理', type: 'slot', value: 'exportData' },
    {
      label: '筛选条件',
      value: 'selectMode',
      type: 'slot',
    },
  ],
})
const batchDataInfo = ref({
  visible: false,
  businessType: '',
  title: '',
  baseData: {
    depotName: '',
    depotId: '',
    deptName: '',
    deptId: '',
    locationNo: '',
    goodsLocationId: '',
  },
})
const infoList = ref({
  data: {},
  fieldList: [
    { label: '单号', value: 'orderNo' },
    {
      label: '盘点仓库',
      value: 'depotName',
    },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
    { label: '状态', value: 'statusValue' },
    { label: '是否子盘点单', value: 'useSubValue' },
    { label: '是否产品零星盘点', value: 'sporadicValue' },
    { label: '是否货位零星盘点', value: 'goodsLocationSporadicValue' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'popover',
    },
  ],
})
// 表格相关
const tableInfo = ref({
  ref: null,
  refresh: 1,
  initCurpage: 1,
  copyData: [],
  data: [],
  isSysGroup: true,
  summary: true,
  summaryFieldList: [
    { value: 'stockQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'diffSumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '保存',
        event: save,
        show: true,
        ifRender: ifRenderSave,
      },
      {
        label: '选择个体',
        event: singleProductDetails,
        show: proxy.$permission('goodsLocationInventory:IndividualModify'),
        ifRender: ifRenderSingle,
      },
      {
        label: '复制行',
        event: addBatchNumber,
        show: true,
        ifRender: ifRenderAddItem,
      },
      {
        label: '切换供应商',
        event: changeSupplier,
        show: true,
        ifRender: function (row) {
          return row.stockCalcQty == 0
        },
      },
      {
        label: '删除',
        event: remove,
        show: true,
        popconfirmText: '删除后将改变数据,是否继续？',
        ifRender: function (row) {
          return row.stockCalcQty === 0
        },
      },
      {
        label: '打印产品码',
        event: printProductCode,
        show: true,
      },
    ],
  },
})
const selectProductSupplier = ref({
  visible: false,
  row: {},
  api: getSupplierProductPage,
  query: {
    id: '',
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})
const fullInfo = ref({
  btnList: [
    { value: 'button', type: 'slot' },
    {
      label: '打印',
      event: print,
      show: proxy.$permission('goodsLocationInventory:printMain'),
    },
    { label: '导出excel', event: exportExcel, show: true },
    { label: '返回', event: returnBank, show: true },
  ],
})
const selectProductInfo = ref({
  visible: false,
  tableKey:
    'wmsStockInventoryQueryProduct-com.slip.spd.entity.vo.core.CoreProductVONew',
  queryParams: {
    orderId: props.tableRow.id,
    codeType: 3,
    // depotId: props.tableRow.depotId
  },
  query: {
    status: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: 1,
    },
    id: {
      queryType: 'NOT_IN',
      queryCategory: 'AND',
      value: '',
    },
    type: {
      asTbName: 'core_product_new',
      columnName: 'type',
      queryResource: 0,
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
    isConsignment: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
  },
})
const individualInfo = ref({
  visible: false,
  query: {
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.tableRow.id,
    },
  },
  productInfo: {},
  saveApi: undefined,
  api: getInventoryDetailsCustomizeListAll,
  delApi: inventoryDetailDelete,
  selectObj: {},
  singleProductIndex: 0,
})
const dataEntryDetailsInfo = ref({
  visible: false,
  title: '',
  tableRow: {},
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const newFullScreenClass = ref('scrollY' + new Date().getTime())
const canExport = computed(() => {
  return tableInfo.value.selections.length
  // tableInfo.value.selections.filter((row) => row.depotStockId <= 0).length ===
  //   0
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
watch(
  () => tableItemInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        const loginUserId = proxy.$store.state.user.userInfo.user.id
        const createUserId = props.tableRow.createUser
        let canSubmit =
          row.status === 1 &&
          (loginUserId === 1 ||
            loginUserId === createUserId ||
            loginUserId === row.createUser)
        row['canSubmit'] = canSubmit
        let canDelete =
          row.status !== 3 &&
          (loginUserId === 1 ||
            loginUserId === createUserId ||
            loginUserId === row.createUser)
        row['canDelete'] = canDelete
      })
    }
  },
  { deep: true }
)
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((item, index) => {
        item.tableIndex = index + 1
      })
    }
    if (val.length && !tableInfo.value.isSysGroup) {
      val.forEach((row) => {
        row.operateSingle = true
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let price = row.price || 0
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        let sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, price),
          unitConvertCoefficient
        )
        let diffCalcQty = proxy.$fn.Subtr(calcQty, row.stockCalcQty)
        let diffSumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(diffCalcQty, price),
          unitConvertCoefficient
        )
        let diffQty = proxy.$fn.accDiv(row.diffCalcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['sumAmount'] = sumAmount
        row['diffSumAmount'] = diffSumAmount
        row['qty'] = qty
        row['diffCalcQty'] = diffCalcQty
        row['diffQty'] = diffQty
      })
    }
    // tableInfo.value.summary = false;
    // proxy.$nextTick(() => {
    //   tableInfo.value.summary = true;
    // });
  },
  { deep: true }
)
function selectGoodsLocation(row) {
  selectLocationNoInfo.value.visible = true
  selectLocationNoInfo.value.row = row
  let data = infoList.value.data
  selectLocationNoInfo.value.query.depotId = data.depotId
  selectLocationNoInfo.value.query.idMult =
    data.inventoryOrderGoodsLocations &&
    data.inventoryOrderGoodsLocations.length
      ? data.inventoryOrderGoodsLocations
          .map((item) => item.goodsLocationId)
          .toString()
      : ''
}
function selectLocationNoCallBack(data) {
  if (data && data.id) {
    tableInfo.value.list[
      selectLocationNoInfo.value.row.tableIndex - 1
    ].locationNo = data.locationNo
    tableInfo.value.list[
      selectLocationNoInfo.value.row.tableIndex - 1
    ].goodsLocationId = data.id
    if (
      tableInfo.value.list[selectLocationNoInfo.value.row.tableIndex - 1]
        .details &&
      tableInfo.value.list[selectLocationNoInfo.value.row.tableIndex - 1]
        .details.length
    ) {
      tableInfo.value.list[
        selectLocationNoInfo.value.row.tableIndex - 1
      ].details.forEach((item) => {
        item.locationNo = data.locationNo
        item.goodsLocationId = item.id
      })
    }
    tableInfo.value.copyData[
      selectLocationNoInfo.value.row.tableIndex - 1
    ].locationNo = data.locationNo
    tableInfo.value.copyData[
      selectLocationNoInfo.value.row.tableIndex - 1
    ].goodsLocationId = data.id
    if (
      tableInfo.value.copyData[selectLocationNoInfo.value.row.tableIndex - 1]
        .details &&
      tableInfo.value.copyData[selectLocationNoInfo.value.row.tableIndex - 1]
        .details.length
    ) {
      tableInfo.value.copyData[
        selectLocationNoInfo.value.row.tableIndex - 1
      ].details.forEach((item) => {
        item.locationNo = data.locationNo
        item.goodsLocationId = item.id
      })
    }
    tableInfo.value.data[
      selectLocationNoInfo.value.row.tableIndex - 1
    ].locationNo = data.locationNo
    tableInfo.value.data[
      selectLocationNoInfo.value.row.tableIndex - 1
    ].goodsLocationId = data.id
    if (
      tableInfo.value.data[selectLocationNoInfo.value.row.tableIndex - 1]
        .details &&
      tableInfo.value.data[selectLocationNoInfo.value.row.tableIndex - 1]
        .details.length
    ) {
      tableInfo.value.data[
        selectLocationNoInfo.value.row.tableIndex - 1
      ].details.forEach((item) => {
        item.locationNo = data.locationNo
        item.goodsLocationId = item.id
      })
    }
  } else {
    tableInfo.value.list[
      selectLocationNoInfo.value.row.tabIndex - 1
    ].locationNo = ''
    tableInfo.value.list[
      selectLocationNoInfo.value.row.tabIndex - 1
    ].goodsLocationId = ''
    if (
      tableInfo.value.list[selectLocationNoInfo.value.row.tableIndex - 1]
        .details &&
      tableInfo.value.list[selectLocationNoInfo.value.row.tableIndex - 1]
        .details.length
    ) {
      tableInfo.value.list[
        selectLocationNoInfo.value.row.tableIndex - 1
      ].details.forEach((item) => {
        item.locationNo = ''
        item.goodsLocationId = ''
      })
    }
    tableInfo.value.copyData[
      selectLocationNoInfo.value.row.tabIndex - 1
    ].locationNo = ''
    tableInfo.value.copyData[
      selectLocationNoInfo.value.row.tabIndex - 1
    ].goodsLocationId = ''
    if (
      tableInfo.value.copyData[selectLocationNoInfo.value.row.tableIndex - 1]
        .details &&
      tableInfo.value.copyData[selectLocationNoInfo.value.row.tableIndex - 1]
        .details.length
    ) {
      tableInfo.value.copyData[
        selectLocationNoInfo.value.row.tableIndex - 1
      ].details.forEach((item) => {
        item.locationNo = ''
        item.goodsLocationId = ''
      })
    }
    tableInfo.value.data[
      selectLocationNoInfo.value.row.tabIndex - 1
    ].locationNo = ''
    tableInfo.value.data[
      selectLocationNoInfo.value.row.tabIndex - 1
    ].goodsLocationId = ''
    if (
      tableInfo.value.data[selectLocationNoInfo.value.row.tableIndex - 1]
        .details &&
      tableInfo.value.data[selectLocationNoInfo.value.row.tableIndex - 1]
        .details.length
    ) {
      tableInfo.value.data[
        selectLocationNoInfo.value.row.tableIndex - 1
      ].details.forEach((item) => {
        item.locationNo = ''
        item.goodsLocationId = ''
      })
    }
  }
}
function selectScanGoodsLocation() {
  selectScanLocationNoInfo.value.visible = true
  let data = infoList.value.data
  selectScanLocationNoInfo.value.query.depotId = data.depotId
  selectScanLocationNoInfo.value.query.idMult =
    data.inventoryOrderGoodsLocations &&
    data.inventoryOrderGoodsLocations.length
      ? data.inventoryOrderGoodsLocations
          .map((item) => item.goodsLocationId)
          .toString()
      : ''
}
function selectScanLocationNoCallBack(data) {
  if (data && data.id) {
    scanFilter.value.locationNo = data.locationNo
  } else {
    scanFilter.value.locationNo = ''
  }
}
function batchDataCallback() {
  //出库处理返回
  getList()
  returnBack()
}
function returnBack() {
  tableInfo.value.selections = []
}
function selectSupplierCallback(data) {
  //供应商返回
  let index = selectProductSupplier.value.row.tableIndex - 1
  if (
    data &&
    Object.keys(data).length &&
    tableInfo.value.data[index].supplierId !== data.supplierId
  ) {
    tableInfo.value.data[index] = {
      ...tableInfo.value.data[index],
      supplierId: data.supplierId,
      supplierName: data.supplierName,
      supplierCode: data.supplierCode,
      price: data.price || 0,
      sumAmount: proxy.$fn.accMul(
        data.price || 0,
        tableInfo.value.data[index].qty
      ),
    }
    if (
      tableInfo.value.data[index].details &&
      tableInfo.value.data[index].details.length
    ) {
      tableInfo.value.data[index].details.forEach((item) => {
        item.supplierId = data.supplierId
        item.supplierName = data.supplierName
        item.supplierCode = data.supplierCode
        item.price = data.price || 0
        item.sumAmount = proxy.$fn.accMul(
          data.price || 0,
          tableInfo.value.data[index].qty
        )
      })
    }
    tableInfo.value.list[index] = {
      ...tableInfo.value.list[index],
      supplierId: data.supplierId,
      supplierName: data.supplierName,
      supplierCode: data.supplierCode,
      price: data.price || 0,
      sumAmount: proxy.$fn.accMul(
        data.price || 0,
        tableInfo.value.list[index].qty
      ),
    }
    if (
      tableInfo.value.list[index].details &&
      tableInfo.value.list[index].details.length
    ) {
      tableInfo.value.list[index].details.forEach((item) => {
        item.supplierId = data.supplierId
        item.supplierName = data.supplierName
        item.supplierCode = data.supplierCode
        item.price = data.price || 0
        item.sumAmount = proxy.$fn.accMul(
          data.price || 0,
          tableInfo.value.list[index].qty
        )
      })
    }
    tableInfo.value.copyData[index] = {
      ...tableInfo.value.copyData[index],
      supplierId: data.supplierId,
      supplierName: data.supplierName,
      supplierCode: data.supplierCode,
      price: data.price || 0,
      sumAmount: proxy.$fn.accMul(
        data.price || 0,
        tableInfo.value.copyData[index].qty
      ),
    }
    if (
      tableInfo.value.copyData[index].details &&
      tableInfo.value.copyData[index].details.length
    ) {
      tableInfo.value.copyData[index].details.forEach((item) => {
        item.supplierId = data.supplierId
        item.supplierName = data.supplierName
        item.supplierCode = data.supplierCode
        item.price = data.price || 0
        item.sumAmount = proxy.$fn.accMul(
          data.price || 0,
          tableInfo.value.copyData[index].qty
        )
      })
    }

    if (tableInfo.value.data[index].id) {
      let api = inventoryDetailsUpdate
      api(tableInfo.value.data[index]).then((res) => {
        if (res && res.success) {
          getList()
        }
      })
    }
  }
}
function revoke(row) {
  subInventoryOrderRevoke([row.id]).then((res) => {
    if (res && res.success) {
      getItemList()
    }
  })
}
//选择供应商
function changeSupplier(row) {
  console.log(row)
  selectProductSupplier.value.visible = true
  selectProductSupplier.value.query.productId = row.productId
  selectProductSupplier.value.query.supplierIdNotIn = row.supplierId
  selectProductSupplier.value.row = row
}
function largeMax(row) {
  let isConsignBusiness = infoList.value.data.isConsignBusiness
  if (isConsignBusiness == 1) {
    if (row.qtyOperateMode === 2) {
      return parseInt(row.stockCalcQty / row.unitConvertCoefficient)
    } else {
      return row.stockCalcQty
    }
  } else {
    if (row.codeType === 2) {
      if (row.stockQty === 0) {
        return 99999999
      } else {
        return 1
      }
    } else if (row.codeType === 3) {
      return 1
    } else {
      return 99999999
    }
  }
}
function smallMax(row) {
  let isConsignBusiness = infoList.value.data.isConsignBusiness
  if (isConsignBusiness == 1) {
    let largeUnitQty = parseInt(row.stockCalcQty / row.unitConvertCoefficient)
    if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
      return parseInt(row.stockCalcQty % row.unitConvertCoefficient)
    } else {
      return row.unitConvertCoefficient - 1
    }
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  if ((row.qtyOperateMode === 2 && row.stockQty > 0) || row.codeType === 3) {
    if (e === 1) {
      row.smallUnitQty = 0
    }
  }
}
function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function changeSmall(e, row) {
  if (row.qtyOperateMode === 2) {
    if ((row.codeType === 2 && row.stockQty > 0) || row.codeType === 3) {
      if (e > 0) {
        row.largeUnitQty = 0
      }
    }
  }
}
function ifRenderSave(row) {
  let isSysGroup = tableInfo.value.isSysGroup
  if (isSysGroup) {
    return row.stockCalcQty == 0 && !getRowAndOldRowKey(row)
  } else {
    return true
  }
}
function ifRenderAddItem(row) {
  return (
    row.id &&
    row.codeType !== 3 &&
    getRowAndOldRowKey(row) &&
    infoList.value.data.isConsignBusiness === 0
  )
}
function getRowAndOldRowKey(row) {
  return (
    row.price +
      '&' +
      row.batchNumber +
      '&' +
      row.validityDate +
      '&' +
      row.productionDate +
      '&' +
      row.locationNo ===
    row.oldPrice +
      '&' +
      row.oldBatchNumber +
      '&' +
      row.oldValidityDate +
      '&' +
      row.oldProductionDate +
      '&' +
      row.oldLocationNo
  )
}
function ifRenderSingle(row) {
  let isSysGroup = tableInfo.value.isSysGroup
  if (isSysGroup) {
    return true
  } else {
    return row.id
  }
}
function singleProductDetails(row, index) {
  individualInfo.value.productInfo = proxy.$fn.deepClone(row)
  let obj = {
    price: 'oldPrice',
    batchNumber: 'oldBatchNumber',
    productionDate: 'oldProductionDate',
    validityDate: 'oldValidityDate',
    oldLocationNo: 'locationNo',
    oldGoodsLocationId: 'goodsLocationId',
  }
  let keys = Object.keys(obj)
  if (tableInfo.value.isSysGroup) {
    for (let key in individualInfo.value.selectObj) {
      if (keys.includes(key) && row.stockCalcQty == 0) {
        individualInfo.value.selectObj[key].value = row[obj[key]]
      } else {
        individualInfo.value.selectObj[key].value = row[key]
      }
    }
  }
  individualInfo.value.query = {
    ...individualInfo.value.query,
    ...individualInfo.value.selectObj,
  }
  if (
    individualInfo.value.query.supplierId &&
    !individualInfo.value.query.supplierId.value
  ) {
    individualInfo.value.query.supplierId.value = -2
  }
  if (row.stockCalcQty == 0) {
    let rowKey = saveKey(row)
    let details = []
    let newRow = proxy.$fn.deepClone(row)
    delete newRow.uuid
    if (row.codeType === 2 || row.codeType === 3 || row.codeType === 4) {
      details = tableInfo.value.data.filter((item) => {
        let newItem = proxy.$fn.deepClone(item)
        delete newItem.uuid
        if (
          newItem.stockCalcQty > 0 &&
          JSON.stringify(newItem) !== JSON.stringify(newRow)
        ) {
          return item
        }
      })
    } else if (row.codeType === 1) {
      details = tableInfo.value.data.filter((item) => {
        let newItem = proxy.$fn.deepClone(item)
        delete newItem.uuid
        if (JSON.stringify(newItem) !== JSON.stringify(newRow)) {
          return item
        }
      })
    }
    let itemIndex = details.findIndex((item, i) => {
      let key = saveKey(item)
      return key === rowKey
    })
    if (itemIndex !== -1) {
      proxy.$alert(
        `该新增或复制行不能与其他行批号效期${
          row.codeType === 4 ? '' : '价格'
        }相同，请修改`,
        '操作提示',
        {
          confirmButtonText: '确定',
        }
      )
      return
    }
  }
  let api = row.id ? inventoryDetailsUpdateByMerge : inventoryDetailsAddProduct
  individualInfo.value.saveApi = api
  individualInfo.value.visible = true
  individualInfo.value.singleProductIndex = index
}
function getForm() {
  getInventoryOrderById(props.tableRow.id).then((res) => {
    if (res && res.success) {
      infoList.value.data = res.data
      selectProductInfo.value.query.isConsignment.value =
        res.data.isConsignBusiness || ''
      scanFilter.value.isConsignment = res.data.isConsignBusiness || ''
      formItemInfo.value.data.isConsignBusiness = res.data.isConsignBusiness
      batchDataInfo.value.baseData = {
        depotName: res.data.depotName,
        depotId: res.data.depotId,
        deptName: res.data.deptName,
        deptId: res.data.deptId,
      }
      // 隐藏冻结数量
      tableInfo.value.fieldList.find(i => {
        if(i.value == 'frozenQty') {
          i.hidden = res.data?.depotAllowFrozenInventory != 1
        }
      })
      getList()
      if (res.data.useSub === 1) {
        getItemList()
      }
    }
  })
}
// 获取列表
function getList() {
  getInventoryDetailsCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      resp.data.forEach((row) => {
        // if (row.depotStockId === -2) {
        row.oldPrice = proxy.$fn.deepClone(row.price)
        row.oldBatchNumber = proxy.$fn.deepClone(row.batchNumber)
        row.oldLocationNo = proxy.$fn.deepClone(row.locationNo)
        row.oldGoodsLocationId = proxy.$fn.deepClone(row.goodsLocationId)
        row.oldProductionDate = proxy.$fn.deepClone(row.productionDate)
        row.oldValidityDate = proxy.$fn.deepClone(row.validityDate)
        // }
        row.key = generateProductKey(row)
      })
      tableInfo.value.data = resp.data
      tableInfo.value.list = tableInfo.value.data.slice(0, 50)
      tableInfo.value.copyData = tableInfo.value.list
      tableInfo.value.loading = false
    }
  })
}
function checkAll() {
  tableInfo.value.data.map((i) => {
    i.qty = i.stockQty
  })
}
// 搜索
function search() {
  //搜索
  const search = filterInfo.value.data.keyword
  if (search) {
    let list = proxy.$fn.deepClone(tableInfo.value.copyData)
    tableInfo.value.list = list.filter((data) => {
      return Object.keys(data).some((key) => {
        if (key === 'qrCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'uniqueCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factorySubCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factoryMainCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'batchNumber') {
          return String(data[key]).indexOf(search) > -1
        }
      })
    })
  } else {
    tableInfo.value.list = tableInfo.value.copyData
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
//出库处理
function exportData(num) {
  let name = false
  let obj = {
    1: '/purch/return',
    2: '/stock/transfer',
    25: '/stock/consume',
    10: '/stock/scrap',
    20: '/use/audit',
    34: '/useReturn/application',
    89: '/wms/cargoSpaceTransfer',
  }
  let routes = proxy.$store.state.permission.routes
  routes.map((item) => {
    if (item.children && item.children.length) {
      item.children.map((i) => {
        if (i.url === obj[num]) {
          name = true
        }
      })
    }
  })
  if (!name) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '你没有相应的菜单权限',
    })
    return
  }
  let param = {
    tableKey:
      'wmsStockInventoryExportData-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      getExportData(data, num)
    }
  })
}
function getExportData(data, num) {
  let list = tableInfo.value.selections.filter(
    (row) => row.stockCalcQty == 0 && !getRowAndOldRowKey(row)
  )
  if (list.toString()) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请勾选有效数据！且保存未保存的数据',
    })
    return
  }
  let ids = tableInfo.value.selections.map((item) => item.groupConcatIds)
  let params = {
    customizeUserVO: data,
    queryMap: {
      diffQty: {
        queryType: 'LESS_THAN',
        value: 0,
      },
      orderId: {
        queryType: 'EQUALS',
        value: props.tableRow.id,
      },
      depotStockId: {
        queryType: 'NOT_EQUAL',
        value: -2,
      },
      id: {
        queryType: 'IN',
        value: ids.toString(),
      },
    },
    queryParams: {
      stockAvailableCalcQtyGt: 0,
      useApplicationId: '',
      isInventoryLossBusiness: num === '20' ? 1 : '',
    },
  }
  getInventoryDetailsCustomizeListAll(params).then((res) => {
    if (res && res.success) {
      if (res.data && res.data.length) {
        if (num === '1') {
          let notSupplierList = []
          res.data.forEach((item) => {
            if (!item.supplierId || item.supplierId === -2) {
              notSupplierList.push(item)
            }
          })
          if (notSupplierList.length) {
            proxy.$message({
              message: `选择采购退货处理的产品存在无供应商的情况，请处理`,
              type: 'warning',
              duration: 3500,
              showClose: true,
            })
            return
          }
        }
        batchDataInfo.value.visible = true
        batchDataInfo.value.businessType = num
        batchDataInfo.value.title = businessTypeOptions.value
          .find((item) => item.code === num)
          .name.replace(/单/g, '')
      } else {
        proxy.$message({
          duration: 3500,
          type: 'warning',
          showClose: true,
          message: '当前勾选产品无盘亏数据，不能出库处理，请重新勾选！',
        })
      }
    }
  })
}
//差异处理
function processDiff() {
  const data = infoList.value.data
  const details = tableInfo.value.data
  data.details = details
  let commonName = data.details
    .filter(
      (detail) =>
        detail.stockQty === 0 &&
        detail.needBatchNumber == '1' &&
        ((!detail.batchNumber && detail.batchNumber !== '0') ||
          !detail.productionDate ||
          !detail.validityDate)
    )
    .map((detail) => detail.commonName)
  if (commonName.length) {
    proxy.$alert(`请输入产品【${commonName}】的批号效期`, '操作提示', {
      confirmButtonText: '确定',
    })
    return
  }
  proxy
    .$confirm('未保存的数据将会丢失，是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      inventoryOrderProcessDiff(data.id).then((resp) => {
        if (resp && resp.success) {
          proxy.$emit('returnModify', {
            ...infoList.value.data,
            selectMode: filterInfo.value.query.selectMode,
          })
          showDialog.value = false
        }
      })
    })
    .catch((e) => {})
}
function selectedIndividualDetails(data) {
  if (data.isCleanProps) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (item) => item.id !== data.id
    )
    tableInfo.value.list = tableInfo.value.list.filter(
      (item) => item.id !== data.id
    )
    tableInfo.value.copyData = tableInfo.value.copyData.filter(
      (item) => item.id !== data.id
    )
    oldDataIndex.value = -1
  } else {
    let itemIndex = individualInfo.value.singleProductIndex
    data = {
      ...data,
      oldPrice: proxy.$fn.deepClone(data.price),
      oldBatchNumber: proxy.$fn.deepClone(data.batchNumber),
      oldLocationNo: proxy.$fn.deepClone(data.locationNo),
      oldGoodsLocationId: proxy.$fn.deepClone(data.goodsLocationId),
      oldProductionDate: proxy.$fn.deepClone(data.productionDate),
      oldValidityDate: proxy.$fn.deepClone(data.validityDate),
    }
    tableInfo.value.list[itemIndex] = data
    tableInfo.value.copyData[data.tableIndex - 1] = data
    tableInfo.value.data[data.tableIndex - 1] = data
    console.log(tableInfo.value.copyData)
    console.log(tableInfo.value.list)
  }
}
//添加批号
function addBatchNumber(row, index) {
  let newData = {
    ...row,
    diffQty: 1,
    diffCalcQty: row.unitConvertCoefficient,
    qty: 1,
    calcQty: row.unitConvertCoefficient,
    stockQty: 0,
    stockCalcQty: 0,
    largeUnitQty: 1,
    smallUnitQty: 0,
    sumAmount: row.price,
    diffSumAmount: row.price,
    id: null,
    depotStockId: -2,
    depotId: props.tableRow.depotId,
    qrCode: '',
    uniqueCode: '',
    factoryMainCode: '',
    isConsignment: '',
    isConsignmentValue: '',
    factorySubCode: '',
    storeBatchNumber: '',
  }
  if (tableInfo.value.isSysGroup) {
    newData.groupConcatIds = ''
    newData.groupSize = 0
  }
  delete newData.key
  delete newData.oldPrice
  delete newData.oldBatchNumber
  delete newData.oldLocationNo
  delete newData.oldGoodsLocationId
  delete newData.oldProductionDate
  delete newData.oldValidityDate
  tableInfo.value.data.splice(row.tableIndex, 0, newData)
  tableInfo.value.list.splice(index + 1, 0, newData)
}
function generateProductKey(item) {
  let key = ''
  if (tableInfo.value.isSysGroup) {
    tableInfo.value.groupList.forEach((row) => {
      key = key + item[row] + '&'
    })
  } else {
    //一物一码带上码校验
    if (item.codeType === 2 || item.codeType === 3 || item.codeType === 4) {
      key =
        item.productId +
        '&' +
        item.batchNumber +
        '&' +
        item.validityDate +
        '&' +
        item.productionDate +
        '&' +
        item.price +
        '&' +
        item.qrCode +
        '&' +
        item.uniqueCode +
        '&' +
        item.factorySubCode +
        '&' +
        item.factoryMainCode +
        '&' +
        item.storeBatchNumber +
        '&' +
        item.locationNo
    } else {
      key =
        item.productId +
        '&' +
        item.batchNumber +
        '&' +
        item.validityDate +
        '&' +
        item.productionDate +
        '&' +
        item.price +
        '&' +
        item.supplierId +
        '&' +
        item.storeBatchNumber +
        '&' +
        item.locationNo
    }
  }
  return key
}
function addProduct() {
  //添加产品
  if (!props.tableRow.deptId) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '该仓库无归属部门，无法操作！',
    })
    return
  }
  let inventoryOrderProducts =
    infoList.value.data.inventoryOrderProducts &&
    infoList.value.data.inventoryOrderProducts.length
      ? infoList.value.data.inventoryOrderProducts
      : []
  if (inventoryOrderProducts.length) {
    if (tableInfo.value.data.length) {
      let arr = _.xorBy(
        inventoryOrderProducts,
        tableInfo.value.data,
        'productId'
      )
      if (arr.length) {
        selectProductInfo.value.query.id.value = arr
          .map((item) => item.productId)
          .toString()
      } else {
        proxy.$message({
          duration: 3500,
          type: 'warning',
          showClose: true,
          message: `无可添加产品`,
        })
        return
      }
    } else {
      selectProductInfo.value.query.id.value = inventoryOrderProducts
        .map((item) => item.productId)
        .toString()
    }
    selectProductInfo.value.query.id.queryType = 'IN'
  } else {
    selectProductInfo.value.query.id.value = tableInfo.value.data.length
      ? tableInfo.value.data.map((item) => item.productId).toString()
      : ''
  }
  selectProductInfo.value.visible = true
}
function selectProduct(row) {
  //过滤保留无码产品
  if (row && row.length) {
    let newData = row.map((item) => {
      return {
        ...item,
        diffQty: 1,
        diffCalcQty: item.unitConvertCoefficient,
        qty: 1,
        calcQty: item.unitConvertCoefficient,
        stockQty: 0,
        stockCalcQty: 0,
        largeUnitQty: 1,
        smallUnitQty: 0,
        sumAmount: item.price,
        diffSumAmount: item.price,
        id: null,
        orderId: props.tableRow.id,
        depotStockId: -2,
        depotId: props.tableRow.depotId,
        qrCode: '',
        uniqueCode: '',
        factoryMainCode: '',
        factorySubCode: '',
        isConsignBusiness: infoList.value.data.isConsignBusiness,
        isConsignBusinessValue: infoList.value.data.isConsignBusinessValue,
        isConsignment: '',
        isConsignmentValue: '',
        storeBatchNumber: '',
        price: item.price || 0,
      }
    })
    tableInfo.value.data = [...newData, ...tableInfo.value.data]
    tableInfo.value.list = tableInfo.value.data.slice(0, 50)
    tableInfo.value.copyData = tableInfo.value.list
  }
}
function remove(row) {
  if (row.id) {
    let selectObj = individualInfo.value.selectObj
    let isSysGroup = tableInfo.value.isSysGroup
    let params = {}
    let api = inventoryDetailsDelete
    if (isSysGroup) {
      for (let key in selectObj) {
        params[key] = row[key]
      }
      params.orderId = props.tableRow.id
      params.id = row.id
      api = inventoryDetailsDeleteByGroups
    }
    api(isSysGroup ? params : [row.id]).then((res) => {
      if (res && res.success) {
        tableInfo.value.list = tableInfo.value.list.filter(
          (item) => item !== row
        )
        tableInfo.value.data = tableInfo.value.data.filter(
          (item) => item !== row
        )
        tableInfo.value.copyData = tableInfo.value.copyData.filter(
          (item) => item !== row
        )
      }
    })
  } else {
    tableInfo.value.data = tableInfo.value.data.filter((item) => item !== row)
    tableInfo.value.list = tableInfo.value.list.filter((item) => item !== row)
    tableInfo.value.copyData = tableInfo.value.copyData.filter(
      (item) => item !== row
    )
  }
  oldDataIndex.value = -1
}
function batchNumberBlur(evet, row, index) {}
function onCallBackScanData(obj) {
  const tableData = tableInfo.value.data
  let { data, flag } = obj
  let curIndex = 0
  tableData.forEach((item) => {
    item.currentScanData = false
  })
  if (flag === 0) {
    data.key = generateProductKey(data)
    let itemIndex = tableData.findIndex((item) => item.key === data.key)
    if (itemIndex !== -1) {
      tableData[itemIndex].largeUnitQty = proxy.$fn.accAdd(
        tableData[itemIndex].largeUnitQty || 0,
        data.largeUnitQty || 0
      )
      tableData[itemIndex].smallUnitQty = proxy.$fn.accAdd(
        tableData[itemIndex].smallUnitQty || 0,
        data.smallUnitQty || 0
      )
      tableData[itemIndex].calcQty = proxy.$fn.accAdd(
        tableData[itemIndex].calcQty || 0,
        data.calcQty || 0
      )
      tableData[itemIndex].qty = proxy.$fn.accDiv(
        tableData[itemIndex].calcQty || 0,
        data.unitConvertCoefficient || 1
      )
      tableData[itemIndex].currentScanData = data.currentScanData
      tableData[itemIndex].sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(
          tableData[itemIndex].calcQty,
          tableData[itemIndex].price || 0
        ),
        data.unitConvertCoefficient || 1
      )
      tableData[itemIndex].diffCalcQty = proxy.$fn.accAdd(
        tableData[itemIndex].diffCalcQty || 0,
        data.calcQty || 0
      )
      tableData[itemIndex].diffQty = proxy.$fn.accDiv(
        tableData[itemIndex].diffCalcQty || 0,
        data.unitConvertCoefficient || 1
      )
      tableData[itemIndex].diffSumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(
          tableData[itemIndex].diffCalcQty,
          tableData[itemIndex].price || 0
        ),
        data.unitConvertCoefficient || 1
      )
    } else {
      data.oldPrice = proxy.$fn.deepClone(data.price)
      data.oldBatchNumber = proxy.$fn.deepClone(data.batchNumber)
      data.oldLocationNo = proxy.$fn.deepClone(data.locationNo)
      data.oldGoodsLocationId = proxy.$fn.deepClone(data.goodsLocationId)
      data.oldProductionDate = proxy.$fn.deepClone(data.productionDate)
      data.oldValidityDate = proxy.$fn.deepClone(data.validityDate)
      tableData[itemIndex] = data
    }
    scrollTable(curIndex, itemIndex)
  } else if (flag === 6) {
    let itemIndex = tableData.findIndex((item) => item.productId === data)
    if (itemIndex !== -1) {
      tableData.forEach((item) => {
        if (item.productId === data) {
          item.currentScanData = true
        }
      })
    }
    scrollTable(curIndex, itemIndex)
  } else if (flag === 15) {
    if (data.stockCalcQty === 0) {
      data = {
        ...data,
        oldPrice: proxy.$fn.deepClone(data.price),
        oldBatchNumber: proxy.$fn.deepClone(data.batchNumber),
        oldLocationNo: proxy.$fn.deepClone(data.locationNo),
        oldGoodsLocationId: proxy.$fn.deepClone(data.goodsLocationId),
        oldProductionDate: proxy.$fn.deepClone(data.productionDate),
        oldValidityDate: proxy.$fn.deepClone(data.validityDate),
      }
    }
    data.key = generateProductKey(data)
    if (tableData.length) {
      let itemIndex = tableData.findIndex((item) => item.key === data.key)
      if (itemIndex !== -1) {
        tableData[itemIndex].largeUnitQty = proxy.$fn.accAdd(
          tableData[itemIndex].largeUnitQty || 0,
          data.largeUnitQty || 0
        )
        tableData[itemIndex].smallUnitQty = proxy.$fn.accAdd(
          tableData[itemIndex].smallUnitQty || 0,
          data.smallUnitQty || 0
        )
        tableData[itemIndex].calcQty = proxy.$fn.accAdd(
          tableData[itemIndex].calcQty || 0,
          data.calcQty || 0
        )
        tableData[itemIndex].qty = proxy.$fn.accDiv(
          tableData[itemIndex].calcQty || 0,
          data.unitConvertCoefficient || 1
        )
        tableData[itemIndex].currentScanData = data.currentScanData
        tableData[itemIndex].sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(
            tableData[itemIndex].calcQty,
            tableData[itemIndex].price || 0
          ),
          data.unitConvertCoefficient || 1
        )
        tableData[itemIndex].diffCalcQty = proxy.$fn.accAdd(
          tableData[itemIndex].diffCalcQty || 0,
          data.calcQty || 0
        )
        tableData[itemIndex].diffQty = proxy.$fn.accDiv(
          tableData[itemIndex].diffCalcQty || 0,
          data.unitConvertCoefficient || 1
        )
        tableData[itemIndex].diffSumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(
            tableData[itemIndex].diffCalcQty,
            tableData[itemIndex].price || 0
          ),
          data.unitConvertCoefficient || 1
        )
        if (tableInfo.value.isSysGroup) {
          tableData[itemIndex].groupConcatIds = tableData[
            itemIndex
          ].groupConcatIds.concat(',' + data.id)
        }

        scrollTable(curIndex, itemIndex)
      } else {
        tableData.unshift(data)
        tableInfo.value.list = tableInfo.value.data.slice(0, 50)
        tableInfo.value.copyData = tableInfo.value.list
        oldDataIndex.value = 1
      }
    } else {
      tableData.unshift(data)
      tableInfo.value.list = tableInfo.value.data.slice(0, 50)
      tableInfo.value.copyData = tableInfo.value.list
      oldDataIndex.value = 1
    }
  }
  proxy.$nextTick(function () {
    let element = document.getElementsByClassName('row' + data.id)[0] || ''
    if (element) {
      element.scrollIntoView(false)
    }
  })
}
function scrollTable(curIndex, itemIndex) {
  curIndex = itemIndex
  listPage.value = Math.floor(curIndex / 50)
  const centerPage = listPage.value * 50
  const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
  const endPage = centerPage + 50
  tableInfo.value.list = tableInfo.value.data.slice(startPage, endPage)
  tableInfo.value.copyData = tableInfo.value.list
  oldDataIndex.value = curIndex
}
function returnBank() {
  //返回
  showDialog.value = false
  proxy.$emit('returnModify')
}
function getItemList() {
  subInventoryOrderAll(filterItemInfo.value.query).then((res) => {
    if (res && res.success) {
      tableItemInfo.value.data = res.data
    }
  })
}
function close() {
  dialogInfo.value.visible = false
  formItemInfo.value.data = {
    remark: '',
    roomNo: '',
    isConsignBusiness: infoList.value.data.isConsignBusiness,
  }
}
function create() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'create'
}
function submit(row) {
  subInventoryOrderSubmit(row.id).then((res) => {
    if (res && res.success) {
      getItemList()
    }
  })
}
// 编辑
function update(data) {
  dialogInfo.value.type = 'update'
  dialogInfo.value.visible = true
  // 显示信息
  formItemInfo.value.data = { ...data }
}
function deleteItem(row) {
  subInventoryOrderBatchDelete([row.id]).then((resp) => {
    if (resp && resp.success) {
      getItemList()
    }
  })
}
function concatData() {
  inventoriesMergeSub(props.tableRow.id).then((res) => {
    if (res && res.success) {
      getForm()
      getItemList()
    }
  })
}
// 初始化验证
function initRules() {
  const formInfo = formItemInfo.value
  formInfo.rules = proxy.$initRules(formInfo.fieldList)
}
function saveItem() {
  const tableInfo = tableItemInfo.value
  const { deptId, depotId, id } = props.tableRow
  formItemInfo.value.ref.validate((valid) => {
    if (valid) {
      let api
      const params = {
        ...formItemInfo.value.data,
        orderId: id,
        deptId,
        depotId,
      }
      const type = dialogInfo.value.type
      if (type === 'create') {
        api = addSubInventoryOrder
      } else if (type === 'update') {
        api = updateSubInventoryOrder
      } else {
        return
      }
      dialogInfo.value.btLoading = true
      proxy
        .$handleAPI(type, api, params)
        .then((res) => {
          if (res.success) {
            dialogInfo.value.visible = false
            tableInfo.refresh = Math.random()
          }
          getItemList()
          close()
          dialogInfo.value.btLoading = false
        })
        .catch((e) => {
          close()
          dialogInfo.value.btLoading = false
        })
    }
  })
}
function dataEntry(row) {
  row.isConsignBusiness = infoList.value.data.isConsignBusiness
  row.isConsignBusinessValue = infoList.value.data.isConsignBusinessValue
  inventoryDataEntryInfo.value.tableRow = { ...row }
  inventoryDataEntryInfo.value.title = '子盘点单数据录入'
  inventoryDataEntryInfo.value.visible = true
}
function getItemDetails(row) {
  row.isConsignBusiness = infoList.value.data.isConsignBusiness
  row.isConsignBusinessValue = infoList.value.data.isConsignBusinessValue
  dataEntryDetailsInfo.value.tableRow = row
  dataEntryDetailsInfo.value.title = '子盘点单详情'
  dataEntryDetailsInfo.value.visible = true
}
function saveKey(item) {
  let key = ''
  if (tableInfo.value.isSysGroup) {
    tableInfo.value.groupList.forEach((row) => {
      if (item.codeType === 4) {
        key = key + (row === 'price' ? '' : item[row] + '&')
      } else {
        key = key + item[row] + '&'
      }
    })
  } else {
    //一物一码带上码校验
    if (item.codeType === 2 || item.codeType === 3) {
      key =
        item.productId +
        '&' +
        item.batchNumber +
        '&' +
        item.validityDate +
        '&' +
        item.productionDate +
        '&' +
        item.price +
        '&' +
        item.qrCode +
        '&' +
        item.uniqueCode +
        '&' +
        item.factorySubCode +
        '&' +
        item.factoryMainCode +
        '&' +
        item.storeBatchNumber +
        '&' +
        item.locationNo
    } else if (item.codeType === 4) {
      key =
        item.productId +
        '&' +
        item.batchNumber +
        '&' +
        item.validityDate +
        '&' +
        item.productionDate +
        '&' +
        item.qrCode +
        '&' +
        item.uniqueCode +
        '&' +
        item.factorySubCode +
        '&' +
        item.factoryMainCode +
        '&' +
        item.storeBatchNumber +
        '&' +
        item.locationNo
    } else {
      key =
        item.productId +
        '&' +
        item.batchNumber +
        '&' +
        item.validityDate +
        '&' +
        item.productionDate +
        '&' +
        item.price +
        '&' +
        item.supplierId +
        '&' +
        item.storeBatchNumber +
        '&' +
        item.locationNo
    }
  }
  return key
}
//暂存
function save(row, index) {
  if (
    row.stockCalcQty == 0 &&
    row.needBatchNumber == '1' &&
    ((!row.batchNumber && row.batchNumber !== '0') ||
      !row.productionDate ||
      !row.validityDate)
  ) {
    proxy.$alert(`请输入产品【${row.commonName}】的批号、效期`, '操作提示', {
      confirmButtonText: '确定',
    })
    return
  }
  if (!row.locationNo) {
    proxy.$alert(`请选择产品【${row.commonName}】的货位编码`, '操作提示', {
      confirmButtonText: '确定',
    })
    return
  }
  if (row.stockCalcQty == 0) {
    let rowKey = saveKey(row)
    let newRow = proxy.$fn.deepClone(row)
    delete newRow.uuid
    let details = []
    if (row.codeType === 2 || row.codeType === 3 || row.codeType === 4) {
      details = tableInfo.value.data.filter((item) => {
        let newItem = proxy.$fn.deepClone(item)
        delete newItem.uuid
        if (
          newItem.stockCalcQty > 0 &&
          JSON.stringify(newItem) !== JSON.stringify(newRow)
        ) {
          return item
        }
      })
    } else if (row.codeType === 1) {
      details = tableInfo.value.data.filter((item) => {
        let newItem = proxy.$fn.deepClone(item)
        delete newItem.uuid
        if (JSON.stringify(newItem) !== JSON.stringify(newRow)) {
          return item
        }
      })
    }
    let itemIndex = details.findIndex((item, i) => {
      let key = saveKey(item)
      return key === rowKey
    })
    if (itemIndex !== -1) {
      proxy.$alert(
        `该新增或复制行不能与其他行批号效期${
          row.codeType === 4 ? '' : '价格'
        }相同，请修改`,
        '操作提示',
        {
          confirmButtonText: '确定',
        }
      )
      return
    }
  }
  let api = row.id ? inventoryDetailsUpdateByMerge : inventoryDetailsAddProduct
  let data = { ...row, orderId: props.tableRow.id, groupConcatIds: row.id }
  if (!tableInfo.value.isSysGroup && row.id) {
    let details = proxy.$fn.deepClone(data)
    data.details = [details]
  }
  let params
  if (!row.id) {
    params = data
  } else {
    params = {
      data: data,
      groupFieldList: tableInfo.value.groupList,
      customizeUserVO: filterInfo.value.query.customizeUserVO,
    }
  }
  api(params).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      data.key = generateProductKey(data)
      delete data.details
      data = {
        ...data,
        oldPrice: proxy.$fn.deepClone(data.price),
        oldBatchNumber: proxy.$fn.deepClone(data.batchNumber),
        oldLocationNo: proxy.$fn.deepClone(data.locationNo),
        oldGoodsLocationId: proxy.$fn.deepClone(data.goodsLocationId),
        oldProductionDate: proxy.$fn.deepClone(data.productionDate),
        oldValidityDate: proxy.$fn.deepClone(data.validityDate),
      }
      tableInfo.value.list[index] = data
      tableInfo.value.copyData[index] = data
      tableInfo.value.data[row.tableIndex - 1] = data
      ElMessage.success({
        duration: 3000,
        showClose: true,
        message: '操作成功',
      })
    }
  })
}
function rowClassName({ row }) {
  let className = 'row' + row.id
  if (row.stockCalcQty < row.calcQty) {
    className += ' warning-row'
  }
  if (row.hasOwnProperty('currentScanData') && row.currentScanData) {
    className += ' light-row'
  }
  return className
}
function handleCallback(data) {
  if (data) {
    proxy.$nextTick(function () {
      const box = document.getElementsByClassName(newFullScreenClass.value)[0]
      box.addEventListener('scroll', handleScroll)
    })
  }
}
function handleScroll() {
  // 获取eagleMapContainer的真实高度
  const box = document.getElementsByClassName(newFullScreenClass.value)[0]
  const boxHeight = box.offsetHeight
  // 获取table_list的真实高度（浮动内容的真实高度）
  const tableHeight = document.getElementById('table-list').offsetHeight
  const tableDom = document.getElementById('table-box')
  // boxHeight和滑块浮动的高度相差小于50 && 不在加载中 && 不是最后一页
  if (
    tableHeight - (box.scrollTop + boxHeight) < 50 &&
    !loading.value &&
    listPage.value + 1 < tableInfo.value.data.length / 50
  ) {
    // 第一次触发时，记录滑块高度
    // data里scrollTop，listPage默认为0
    if (!scrollTop.value) {
      scrollTop.value = box.scrollTop
    }
    // 触发下拉加载更多
    queryMoreStat(true, tableHeight, boxHeight)
  } else if (box.scrollTop <= tableDom.offsetTop + 200 && !loading.value) {
    // 如果滑块上拉到顶部，则向上加载50条
    queryMoreStat(false, tableHeight, boxHeight)
  }
}
function queryMoreStat(type, tableHeight, boxHeight) {
  loading.value = true
  // 触底加载
  const tableData = tableInfo.value.data
  if (type) {
    listPage.value = listPage.value + 1
    const centerPage = listPage.value * 50
    const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
    const endPage = centerPage + 50
    const newList = tableData.slice(startPage, endPage)
    if (listPage.value > 0) {
      const box = document.getElementsByClassName(newFullScreenClass.value)[0]
      // 视图跳到触发的数据，补回50的高度差值
      box.scrollTop = scrollTop.value - 50
    }
    tableInfo.value.list = newList
    tableInfo.value.copyData = tableInfo.value.list
  } else {
    // 置顶加载
    if (listPage.value > 0) {
      listPage.value = listPage.value - 1
      const centerPage = listPage.value * 50
      const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
      const endPage = centerPage + 50
      const newList = tableData.slice(startPage, endPage)
      if (listPage.value > 0) {
        const tableDom = document.getElementById('table-box')
        const box = document.getElementsByClassName(newFullScreenClass.value)[0]
        // box.scrollTop = tableHeight - scrollTop.value - boxHeight

        box.scrollTop = tableDom.offsetTop + 220
      }
      tableInfo.value.list = newList
      tableInfo.value.copyData = tableInfo.value.list
    } else {
      tableInfo.value.list = tableData.slice(0, 50)
      tableInfo.value.copyData = tableInfo.value.list
    }
  }
  proxy.$nextTick(() => {
    loading.value = false
  })
}

function indexMethod(row) {
  // const centerPage = listPage.value * 50
  // const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
  // return startPage + index + 1;
  return row.tableIndex
}

function getSummaries({ columns, data }) {
  const sums = []
  const tableData = tableInfo.value.data
  const summaryFieldList = tableInfo.value.summaryFieldList
  if (summaryFieldList.length === 0) return sums
  columns.forEach((column, index) => {
    let arrIndex = -1
    if (typeof summaryFieldList[0] === 'string') {
      arrIndex = _.findIndex(summaryFieldList, column.property)
    } else if (typeof summaryFieldList[0] === 'object') {
      arrIndex = _.findIndex(summaryFieldList, function (o) {
        return o.value === column.property
      })
    }
    if (arrIndex !== -1) {
      const values = tableData.map((item) => Number(item[column.property]))
      let formatter = summaryFieldList[arrIndex].formatter || ''
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            if (formatter) {
              return proxy.$fn.accAdd(
                proxy.$fn.TripartiteReturnNumber(formatter(prev)),
                proxy.$fn.TripartiteReturnNumber(formatter(curr))
              )
            } else {
              return proxy.$fn.accAdd(prev, curr)
            }
          } else {
            return prev
          }
        }, 0)
        if (formatter) {
          sums[index] = formatter(sums[index])
        }
      } else {
        sums[index] = ''
      }
    }
  })
  // if (checkBox.value) {
  //   sums[1] = "合计";
  // } else {
  sums[0] = '合计'
  // }
  return sums
}

function debounce(fn, delay) {
  let timer = null
  return function () {
    if (timer !== null) {
      clearTimeout(timer)
    }
    timer = setTimeout(fn, delay)
  }
}
function throttle(fn, delay) {
  let timer = null,
    startTime = new Date()
  return function () {
    let curTime = new Date()
    let remaining = delay - (curTime - startTime)
    clearTimeout(timer)
    if (remaining <= 0) {
      startTime = new Date()
      fn.apply(proxy, arguments)
    } else {
      timer = setTimeout(fn, remaining)
    }
  }
}

function updateProduct(row) {
  inventoryDetailsUpdate(row).then((res) => {
    if (res && res.success) {
    }
  })
}
function printProductCode(row) {
  let data = []
  if (row && row.productId) {
    data.push(row.productId)
  }
  if (data.length) {
    productCodePrint(data).then((res) => {
      if (res && res.success) {
        printerInfo.value.visible = true
        printerInfo.value.data = res.data
      }
    })
  }
}
function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function print() {
  fatchTemplateByCode({
    resourceCode: 'goodsLocationInventory:printMain',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp)
    }
  })
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'wmsStockInventoryDataEntry-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO',
    orderIds: [props.tableRow.id],
    queryParams: filterInfo.value.query.queryParams,
  }
  getInventoryOrderPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('goodsLocationInventory:price')
      )
    }
  })
}
function exportExcel() {
  inventoriesExcel(filterInfo.value.query).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'wmsStockInventoryDataEntry-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let obj = {}
      tableInfo.value.groupList = []
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      tableInfo.value.isSysGroup = false
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.value.isSysGroup = true
          tableInfo.value.groupList.push(key)
          obj[key] = {
            queryType: 'EQUALS',
            queryCategory: 'AND',
            ignoreEmptyValue: false,
            value: null,
          }
        }
      }
      individualInfo.value.selectObj = obj
      filterInfo.value.query.customizeUserVO = data
      if (props.tableRow.id) {
        getForm()
      }
    }
  })
}

let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'slot',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('goodsLocationInventory:price'),
    hidden: true,
  },
  sumAmount: {
    label: '盘点金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('goodsLocationInventory:price'),
    hidden: true,
    show: false,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('goodsLocationInventory:price'),
    hidden: true,
    show: false,
  },
  diffQty: {
    label: '差异数量',
    value: 'diffQty',
    type: 'column',
    formatter: proxy.$fn.qtyFormatter,
    handle: true,
    show: false,
  },
  diffSumAmount: {
    label: '盘点差异金额',
    value: 'diffSumAmount',
    type: 'column',
    permission: !proxy.$permission('goodsLocationInventory:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
  batchNumber: {
    label: '生产批号',
    value: 'batchNumber',
    type: 'slot',
    hidden: true,
    show: false,
  },
  productionDate: {
    label: '生产日期',
    value: 'productionDate',
    type: 'slot',
    hidden: true,
    show: false,
  },
  validityDate: {
    label: '失效日期',
    value: 'validityDate',
    type: 'slot',
    hidden: true,
    show: false,
  },
  locationNo: {
    label: '货位编号',
    value: 'locationNo',
    type: 'slot',
    hidden: true,
    show: false,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
onMounted(() => {
  initRules()
  box.value = document.getElementsByClassName(newFullScreenClass.value)[0]
  box.value && box.value.addEventListener('scroll', throttle(handleScroll, 30))
  console.log(box.value)
  formRefs.value = [proxy.$refs['tableForm']]
})
onBeforeUnmount(() => {
  box.value &&
    box.value.removeEventListener('scroll', throttle(handleScroll, 30))
})
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow-y: hidden;
}
:deep(.el-table).warning-row {
  background: #f7c1c1 !important;
}
:deep(.el-table) .light-row {
  background: #c3f1d6 !important;
}
</style>
